window['WS'] = {
    ws: null,
    port: "<?php echo GATEWAY_PORT;?>",
    connect: function (port) {
        if (port) this.port = port;

        // 创建websocket
        this.ws = new WebSocket("ws://" + document.domain + ":" + this.port);
        // 当socket连接打开时，输入用户名
        this.ws.onopen = this.onopen;
        // 当有消息时根据消息类型显示不同信息
        this.ws.onmessage = this.onmessage;
        this.ws.onclose = this.onclose;
        this.ws.onerror = this.onerror;

        //接管表单提交
        var _this = this;
        $('form button[type="submit"]').attr('type', 'button');
        $('form button').unbind().click(function () {
            var form = $(this).parents('form');
            window['WS'].saveFormVars(form);
            var data = form.serializeArray();
            data.push({name: 'token', value: $('#api_token').val()});

            var msg = {};
            for (i in data) {
                msg[data[i]['name']] = data[i]['value'];
            }
            _this.send(JSON.stringify(msg));
        });
    },
    onopen: function () {
        window['WS'].print("--->连接成功");
    },
    onmessage: function (e) {
        window['WS'].print('<---response:' + JSON.stringify(JSON.parse(e.data), null, 4));
    },
    onclose: function () {
        window['WS'].print("<---连接关闭，重试中...");
        setTimeout(function () {
            window['WS'].connect(window['WS'].port);
        }, 1000)
    },
    onerror: function () {
        window['WS'].print("出现错误");
    },
    send: function (msg) {
        window['WS'].print('--->request:' + JSON.stringify(JSON.parse(msg), null, 4));
        this.ws.send(msg);
    },
    print: function (str) {
        $('#output').append(str + "\n\n\n");
        setTimeout(function () {
            var top = $('#output').parent().get(0).scrollHeight;
            $('#output').parent().scrollTop(top);
        }, 100);
    },
    saveFormVars: function (form) {
        var el = form;
        var action = el.attr('data-action');
        el.find('input').each(function () {
            var i = $(this);
            if (i.is('[type=checkbox]') || i.is('[type=file]')) {
                return true;
            }
            $.cookie(action + '-' + i.attr('name'), i.val(), {expires: 30});
            if (window.localStorage) {
                window.localStorage.setItem(action + '-' + i.attr('name'), i.val())
            }
        });
    }
}